﻿using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Windows;
using Flurl.Http;
using hygge_imaotai.Domain;
using hygge_imaotai.Entity;
using hygge_imaotai.UserInterface.Component;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NLog;

namespace hygge_imaotai.UserInterface.UserControls {
    /// <summary>
    /// AppointProjectUserControl.xaml 的交互逻辑
    /// </summary>
    public partial class AppointProjectUserControl : System.Windows.Controls.UserControl {
        private static readonly Logger Log = LogManager.GetCurrentClassLogger();

        public AppointProjectUserControl() {
            InitializeComponent();
            DataContext = new AppointProjectViewModel();
        }

        private void SearchButton_OnClick(object sender, RoutedEventArgs e) {
            // 判断productListFile是否存在,存在则读入缓存
            if (!File.Exists(App._productListFile)) {
                new MessageBoxCustom("请先刷新商品列表", MessageType.Error, MessageButtons.Ok).ShowDialog();
                return;
            }
            var json = File.ReadAllText(App._productListFile);
            AppointProjectViewModel.ProductList = JsonConvert.DeserializeObject<ObservableCollection<ProductEntity>>(json);
        }

        /// <summary>
        /// 刷新商品列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void RefreshProductButton_OnClick(object sender, RoutedEventArgs e) {
            try {
                App.MtSessionId = string.Empty;
                App.WriteCache("mtSessionId.txt", string.Empty);
                AppointProjectViewModel.ProductList.Clear();
                await IMTService.GetCurrentSessionId();
                new MessageBoxCustom("刷新完成，重新打开即可看到最新列表。", MessageType.Info, MessageButtons.Ok).ShowDialog();

                SearchButton_OnClick(sender, e);
            }
            catch (Exception ex) {
                Log.Error(ex);
                MessageBox.Show(ex.Message, "出错啦", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }
}
